package com.greenDao.activity.tool.button.movie;

import java.sql.SQLException;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.greenDao.activity.tool.DatabaseUtils;
import com.greenDao.activity.tool.GuiUtils;
import com.greenDao.activity.tool.LogUtils;
import com.greenDao.activity.tool.Utils;
import com.greenDao.db.GreenDaoHelper;
import com.greenDao.pojo.Movie;
import com.greenDao.pojo.MovieDao;
import com.greenDao.pojo.MovieDao.Properties;
import com.greenDao.pojo.PojoUtils;

import de.greenrobot.dao.query.Query;
import de.greenrobot.dao.query.QueryBuilder;

public class AddMovieButton implements View.OnClickListener {

	private final Activity activity;
	private final EditText[] edits;

	public AddMovieButton(Activity activity, EditText... edits) {
		this.activity = activity;
		this.edits = edits;
	}

	@Override
	public void onClick(View v) {

		Movie movie = PojoUtils.createMovie(edits);
		if (Utils.checkMovieFields(movie)) {
			GuiUtils.showAlertDialog(activity, "The only field which can be empty is 'rate', try again");
			return;
		}
		// LogUtils.logMovieEntity(movie);

		MovieDao movieDao = GreenDaoHelper.getMovieDao();
		try {
			Query<Movie> queryBuilder = buildQuery(movieDao, movie);
			if (!queryBuilder.list().isEmpty()) {
				GuiUtils.showAlertDialog(activity, "You can't add movie with data that arleady exists");
				return;
			}
		} catch (SQLException ex) {
			Log.e("query builder", "sql exception occured", ex);
		}
		DatabaseUtils.saveMovie(movie);
		LogUtils.logAllMovies(movieDao.loadAll());

		activity.finish();
	}

	// @formatter:off
	private Query<Movie> buildQuery(MovieDao movieDao, Movie movie)
			throws SQLException {
		QueryBuilder<Movie> queryBuilder = movieDao.queryBuilder();
		queryBuilder
			.where(
					Properties.Title.eq(movie.getTitle()), 
					Properties.Year.eq(movie.getYear()));
		return queryBuilder.build();
	}
	// @formatter:on
}
